import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/services.dart';
import 'package:flutter_union_pay/enum/union_pay_enum.dart';
import 'package:flutter_union_pay/model/payment_result_model.dart';
import 'package:flutter_union_pay/union_pay.dart';

class UnionPayService {
  /// 获取云闪付平台版本信息

  static Future<String> getPlatformVersion() async {
    try {
      String platformVersion = await UnionPay.uPayVersion();
      logger.i("UnionPay platform version: $platformVersion");
      return platformVersion;
    } on PlatformException catch (e) {
      logger.e("Failed to get platform version: $e");
      return 'Failed to get platform version.';
    } catch (e) {
      logger.e("Unknown error occurred while fetching platform version: $e");
      return 'Error occurred.';
    }
  }

  /// 检查是否安装了云闪付App
  static Future<bool> isInstalled({
    required PaymentEnv env,
    required String merchantInfo,
  }) async {
    try {
      bool isInstalled = await UnionPay.isInstalled(
        mode: env,
        merchantInfo: merchantInfo,
      );
      logger.i("Is UnionPay App installed: $isInstalled");
      return isInstalled;
    } on PlatformException catch (e) {
      logger.e("Failed to check UnionPay installation: $e");
      return false;
    } catch (e) {
      logger.e("Unknown error occurred while checking installation: $e");
      return false;
    }
  }

  /// 调用云闪付进行支付
  static Future<void> pay({
    required PaymentEnv env,
    required String tn,
    required String scheme,
  }) async {
    try {
      final result = await UnionPay.pay(
        mode: env,
        tn: tn,
        scheme: scheme,
      );
      logger.i("UnionPay payment result: $result ？'支付成功': '支付失败' ");
    } on PlatformException catch (e) {
      logger.e("Payment initiation failed: $e");
    } catch (e) {
      logger.e("Unknown error occurred while initiating payment: $e");
    }
  }

  /// 注册支付结果的回调监听器
  /// 注册支付结果的回调监听器
  static void registerPayListener(Function(PaymentResult result) onPaymentResult) {
    UnionPay.payListener((result) {
      logger.i("Payment result: Status: ${result.status}, Code: ${result.code}");

      // 调用传入的回调函数
      onPaymentResult(result);
    });
  }
}
